package com.stone.serverless.registry.service;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.stone.serverless.registry.DiscoveryService;
import com.stone.serverless.registry.NacosComponentProvider;
import com.stone.serverless.registry.domain.ServiceInstance;
import com.stone.serverless.sdk.utils.JsonUtil;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/24 18:16
 * @Version: 1.0.0
 */
@Component
public class DiscoveryServiceImpl implements DiscoveryService {

    @NacosInjected
    private NamingService namingService;

    @PostConstruct
    public void init() {
        NacosComponentProvider.INSTANCE.add(this);
    }

    @SneakyThrows
    @Override
    public List<ServiceInstance> getAllService(String serviceName) {
        List<Instance> allInstances = namingService.getAllInstances(serviceName);
        return JsonUtil.toList(JsonUtil.toStr(allInstances), ServiceInstance.class);
    }

    @SneakyThrows
    @Override
    public void registerInstance(String serviceName, String ip, int port) {
        namingService.registerInstance(serviceName, ip, port);
    }

    @SneakyThrows
    @Override
    public void registerInstance(String serviceName, ServiceInstance serviceInstance) {
        Instance instance = JsonUtil.toBean(JsonUtil.toStr(serviceInstance), Instance.class);
        namingService.registerInstance(serviceName, instance);
    }

    @SneakyThrows
    @Override
    public void registerInstance(String serviceName,String version, String ip, int port, Map<String, String> metadata) {
        Instance instance = new Instance();
        instance.setIp(ip);
        instance.setPort(port);
        instance.setInstanceId(serviceName+"_"+version);
        instance.setMetadata(metadata);
        namingService.registerInstance(serviceName, instance);
    }

    @SneakyThrows
    @Override
    public List<ServiceInstance> selectInstances(String serviceId, boolean healthy) {
        List<Instance> instances = namingService.selectInstances(serviceId, healthy);
        return JsonUtil.toList(JsonUtil.toStr(instances), ServiceInstance.class);
    }


    @SneakyThrows
    @Override
    public void deregisterInstance(String serviceName, String ip, int port) {
        namingService.deregisterInstance(serviceName, ip,port);
    }

}
